package com.program.config;

import com.program.bean.UserBean;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenticationFilter extends FormAuthenticationFilter {

    public AuthenticationFilter() {
        super();
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o)  {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //预检请求过滤
        if ("OPTIONS".equals(req.getMethod())){
            resp.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }

        return super.isAccessAllowed(servletRequest,servletResponse,o);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse resp = WebUtils.toHttp(response);
        HttpServletRequest req = WebUtils.toHttp(request);

        System.out.println("-------------------------------"+req.getHeader("Referer"));
        resp.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.addHeader("Access-Control-Allow-Headers", "*");
        resp.addHeader("Access-Control-Allow-Methods", "*");
        resp.addHeader("Access-Control-Allow-Credentials", "true");

        if (isLoginRequest(request, response)) {
            return true;
        } else {
            WebUtils.toHttp(response).sendRedirect("/unauth");
            return false;
        }


    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        // 获取已登录的用户信息
        UserBean activeUser = (UserBean) subject.getPrincipal();
        // 获取session
        HttpServletRequest req = WebUtils.toHttp(request);
        HttpSession session = req.getSession();

        // 把用户信息保存到session
        session.setAttribute("activeUser", activeUser);
        return super.onLoginSuccess(token, subject, request, response);
    }
}